﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Ionic.Zip;
using Microsoft.AspNetCore.Mvc;
using SXFramWork.Core;
using SXFramWork.Service;

namespace SXFramWork.API.Controllers.Admin
{

    /// <summary>
    /// 代码生成
    /// </summary>
    public class CodeGeneratorController : WebController
    {
        private readonly ICodeGenerratorService _service;
        private readonly ILoginInfo _loginInfo;
        public CodeGeneratorController(ICodeGenerratorService codeGenerratorService,ILoginInfo loginInfo)
        {
            _loginInfo = loginInfo;
            _service = codeGenerratorService;
        }
        /// <summary>
        /// 查询数据表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Menu("代码生成")]
        public async Task<IApiResult> List()
        {
            return await _service.GetTables();
        }
        /// <summary>
        /// 查询数据库表的列
        /// </summary>
        /// <param name="tableName"></param>
        /// <returns></returns>
        [HttpGet]
        [Power("查询数据库表的列")]
        public async Task<IApiResult> QueryTableColumn([FromQuery] string tableName)
        {
            return await _service.GetTableColumn(tableName);
        }
        /// <summary>
        /// 代码生成
        /// </summary>
        /// <param name="tableNames"></param>
        /// <returns></returns>
        [HttpPost]
        [Power("生成代码")]
        public async Task<IActionResult> CreateCode( [FromBody]List<string> tableNames)
        {
            var result= await _service.BuildCode(tableNames);
            var filePath = "";
           
            using (ZipFile zip = new ZipFile(Encoding.UTF8))
            {
                zip.UseZip64WhenSaving = Zip64Option.AsNecessary;
                zip.CompressionMethod = CompressionMethod.Deflate;
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestSpeed;
                zip.AddDirectory(result.Data);
                var dirPath = result.Data.Substring(0, result.Data.LastIndexOf(Path.DirectorySeparatorChar));
                 filePath = Path.Combine(dirPath,_loginInfo.UserId+"_"+ DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip");
              
                await Task.Run(() => zip.Save(filePath));
            }
            Directory.Delete(result.Data,true);
            return PhysicalFile(filePath, "application/octet-stream", HttpUtility.UrlEncode( "模板代码-" +DateTime.Now.ToString("yyyyMMddHHmmss")+".zip",Encoding.UTF8), true);
        }
    }
}